<?php

namespace App\Core;

class Router
{
    private array $routes = [];
    private array $middlewares = [];

    public function get(string $path, $handler, bool $requiresAuth = false): void
    {
        $this->addRoute('GET', $path, $handler, $requiresAuth);
    }

    public function post(string $path, $handler, bool $requiresAuth = false): void
    {
        $this->addRoute('POST', $path, $handler, $requiresAuth);
    }

    public function put(string $path, $handler, bool $requiresAuth = false): void
    {
        $this->addRoute('PUT', $path, $handler, $requiresAuth);
    }

    public function delete(string $path, $handler, bool $requiresAuth = false): void
    {
        $this->addRoute('DELETE', $path, $handler, $requiresAuth);
    }

    private function addRoute(string $method, string $path, $handler, bool $requiresAuth = false): void
    {
        $this->routes[] = [
            'method' => $method,
            'path' => $path,
            'handler' => $handler,
            'requiresAuth' => $requiresAuth
        ];
    }

    public function middleware($middleware): void
    {
        $this->middlewares[] = $middleware;
    }

    public function dispatch(): void
    {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        
        // 移除 /api 前缀（如果有）
        $path = preg_replace('#^/api#', '', $path);
        
        // 查找匹配的路由
        foreach ($this->routes as $route) {
            if ($route['method'] !== $method) {
                continue;
            }

            $pattern = $this->convertPathToRegex($route['path']);
            
            if (preg_match($pattern, $path, $matches)) {
                array_shift($matches); // 移除完整匹配
                
                // 只对需要认证的路由执行中间件
                if ($route['requiresAuth']) {
                    foreach ($this->middlewares as $middleware) {
                        if (is_callable($middleware)) {
                            $middleware();
                        } elseif (is_string($middleware)) {
                            $middlewareObj = new $middleware();
                            $middlewareObj->handle();
                        }
                    }
                }
                
                // 执行处理器
                $handler = $route['handler'];
                
                if (is_callable($handler)) {
                    call_user_func_array($handler, $matches);
                } elseif (is_array($handler)) {
                    [$controller, $method] = $handler;
                    $controllerObj = new $controller();
                    call_user_func_array([$controllerObj, $method], $matches);
                }
                
                return;
            }
        }
        
        Response::error('接口不存在', 404);
    }

    private function convertPathToRegex(string $path): string
    {
        // 转换路径参数 :param 为正则表达式
        $pattern = preg_replace('#:(\w+)#', '([^/]+)', $path);
        return '#^' . $pattern . '$#';
    }
}

